/**
 * 
 * @param {*} lists 需要打印的数组
 * @param {*} printerNum 打印机对应编号
 * @param {*} type 打印 true/预览 false
 */
import { MessageBox } from 'element-ui'
import { getLodop ,needCLodop} from '@/utils/LodopFuncs.js'
import { parseTime } from '@/utils/ruoyi'
import { getPrinterByIpAndPrinterType } from "@/api/system/printer";
import { genCirculationRegister, genDosageNotification } from "@/api/slides/task";
import { blobToBase64 } from "@/utils/file";

export async function printCode(lists, printerNum, type = false, showTime = false) {
  const printList = [...lists]
  if(needCLodop()) {
    try {
      let LODOP = getLodop();

      // 查询打印机
      await getPrinterByIpAndPrinterType(printerNum).then((responsePrinter) => {
        LODOP.SET_PRINT_MODE('WINDOW_DEFPRINTER', responsePrinter.rows[0].printerName)
        LODOP.SET_PRINTER_INDEXA(responsePrinter.rows[0].printerName);
      });
      
      LODOP.PRINT_INIT('条码编号')

      console.log("---------", LODOP.GET_PRINTER_NAME(0));
      console.log("---------", LODOP.GET_PRINTER_NAME(1));
      console.log("---------", LODOP.GET_PRINTER_COUNT());
      console.log("---------PaperLength", LODOP.GET_PRINTER_NAME("0:PaperLength"));
      console.log("---------PaperWidth", LODOP.GET_PRINTER_NAME("0:PaperWidth"));
      console.log("---------MaxExtentWidth", LODOP.GET_PRINTER_NAME("0:MaxExtentWidth"));
      console.log("---------PaperSize", LODOP.GET_PRINTER_NAME("0:PaperSize"));
      console.log("---------PortName", LODOP.GET_PRINTER_NAME("0:PortName"));
      console.log("---------MinExtentWidth", LODOP.GET_PRINTER_NAME("0:MinExtentWidth"));
      console.log("---------Copies", LODOP.GET_PRINTER_NAME("0:Copies"));
      // console.log("---------", LODOP.GET_PRINTER_NAME("1:MaxExtentWidth"));

        let num = Math.ceil(printList.length / 2)
        LODOP.SET_PRINT_PAGESIZE(1, `7.8cm`, `${30}mm`,"");
        LODOP.SET_PRINT_MODE('POS_BASEON_PAPER', true)
        printList.forEach((item, index) => {
          console.log(index);
          
          // 设置每两条数据创建纸张
          let xStandard = index % 2 == 0 ? 0 : 40 // 纸张x轴
          let yMultiple = Math.ceil((index + 1) / 2) // 行数倍率
          // let yStandard = 0 // y轴偏移量
          let yStandard = (yMultiple - 1) * 15 // y轴偏移量

          // let xAvatar = j % 2 == 0 ? '70mm' : '175mm' // 人像x轴
          // let xSignet = j % 2 == 0 ? '45mm' : '150mm' // 印章x轴
          // let yAvatar = `${15 + yMultiple * 55}mm` // 人像y轴
          // let ySignet = `${15 + yMultiple * 55}mm` // 印章y轴

          let offset = xStandard; /* 水平便宜量 */
          let offsetOri = yStandard; /* 垂直偏移量 */
          
          // 二维码---------------------------------------------
          LODOP.ADD_PRINT_BARCODE(`${offsetOri}mm`, `${2 + offset}mm`, "32mm", "5mm", "128Auto", item.dosageNumber);
          LODOP.SET_PRINT_STYLEA(0, "FontSize", 6);
          // 委托单位------------------------------------
          item.entrustOrganizationName = item.entrustOrganizationName?.length > 10 ? 
                                          (item.entrustOrganizationName.slice(0, 9) + '...') : 
                                          item.entrustOrganizationName
          LODOP.ADD_PRINT_TEXT(`${6 + offsetOri}mm`, `${2 + offset}mm`, "100%", "100%", item.entrustOrganizationName || "");
          // LODOP.SET_PRINT_STYLEA(0, "FontSize", );
          LODOP.SET_PRINT_STYLEA(0, "FontSize", 6);
          // 姓名------------------------------------
          LODOP.ADD_PRINT_TEXT(`${6 + offsetOri}mm`, `${26 + offset}mm`,"100%","100%", `${item.personnelName || ''}` + `${item.dosageType == "1" ? '(内)' :
                                                                                                                          item.dosageType == "2" ? '(外)' : ''}`);
          LODOP.SET_PRINT_STYLEA(0, "FontSize", 8);

          // 时间------------------------------------
          LODOP.ADD_PRINT_TEXT(`${9 + offsetOri}mm`, `${2 + offset}mm`,"100%","100%", `${parseTime(item.wearingBeginTime, "{y}/{m}/{d}")}-${parseTime(item.wearingEndTime, "{y}/{m}/{d}")}`);
          LODOP.SET_PRINT_STYLEA(0, "FontSize", 8);
          LODOP.SET_PRINT_STYLEA(0, "Bold" , 1);
          if ((index + 1) % 4 == 0) {
            // LODOP.NEWPAGE();
          }
        });
      if (type) {
        LODOP.PREVIEW();
      } else {
        LODOP.PRINT();
      }
    } catch (error) {
      console.log("error", error);
      MessageBox.$alert(`检测到您还未安装C-LODOP套打控件,请确认启用后再打印。或您可点击下载该套打控件，安装成功后刷新页面再进行打印`, '提示', {
        confirmButtonText: '确定',
        callback: action => {
          window.open('https://www.lodop.net/download.html' );
        }
      });
    }
  }
}

// 流转登记表
export async function handlePrintTurnoverRegister(taskPersonalDosimeterId, printerNum, type = false) {
  let LODOP = getLodop()

  // 查询打印机
  await getPrinterByIpAndPrinterType(printerNum).then((responsePrinter) => {
    LODOP.SET_PRINT_MODE('WINDOW_DEFPRINTER', responsePrinter.rows[0].printerName)
    LODOP.SET_PRINTER_INDEXA(responsePrinter.rows[0].printerName);
  });
  
  LODOP.PRINT_INIT('流转登记表')
  LODOP.SET_PRINT_PAGESIZE(1, 0, 0, 'A4')

  genCirculationRegister(taskPersonalDosimeterId).then(response => {
    // console.log(response);
    // listByIds(res.data).then((response) => {
    // 	window.open(response.data[0].url, 'pdf')
    // });
    let binaryData = []
    binaryData.push(response.data)
    blobToBase64(
      new Blob(binaryData, { type: 'application/pdf' })
    ).then((res) => {
      LODOP.ADD_PRINT_PDF(
        '0',
        '0',
        '100%',
        '100%',
        res.split('data:application/pdf;base64,')[1]
      )
      // console.log(res);
      // 设置对后台打印状态进行捕获
      // LODOP.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
      if (type) {
        LODOP.PRINT();
      } else {
        LODOP.PREVIEW();
      }
    })
  })
}

// 告知书
export async function handlePrintNotice(taskPersonalDosimeterId, printerNum, type = false) {
  let LODOP = getLodop()

  // 查询打印机
  await getPrinterByIpAndPrinterType(printerNum).then((responsePrinter) => {
    LODOP.SET_PRINT_MODE('WINDOW_DEFPRINTER', responsePrinter.rows[0].printerName)
    LODOP.SET_PRINTER_INDEXA(responsePrinter.rows[0].printerName);
  });
  
  LODOP.PRINT_INIT('告知书')
  LODOP.SET_PRINT_PAGESIZE(1, 0, 0, 'A4')

  genDosageNotification(taskPersonalDosimeterId).then(response => {
    // console.log(response);
    // listByIds(res.data).then((response) => {
    // 	window.open(response.data[0].url, 'pdf')
    // });
    let binaryData = []
    binaryData.push(response.data)
    blobToBase64(
      new Blob(binaryData, { type: 'application/pdf' })
    ).then((res) => {
      LODOP.ADD_PRINT_PDF(
        '0',
        '0',
        '100%',
        '100%',
        res.split('data:application/pdf;base64,')[1]
      )
      // console.log(res);
      // 设置对后台打印状态进行捕获
      // LODOP.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
      if (type) {
        LODOP.PRINT();
      } else {
        LODOP.PREVIEW();
      }
    })
  })
}